package net.guerlab.smart.wx.web.controller.wx;

import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import net.guerlab.commons.collection.CollectionUtil;
import net.guerlab.smart.wx.core.domain.WxUserDTO;
import net.guerlab.smart.wx.core.exception.WxUserInvalidException;
import net.guerlab.smart.wx.core.searchparams.WxUserSearchParams;
import net.guerlab.smart.wx.service.entity.WxUser;
import net.guerlab.smart.wx.service.service.WxUserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.Collection;
import java.util.Collections;
import java.util.Map;

/**
 * 微信用户
 *
 * @author guer
 */
@Api(tags = "微信用户")
@RestController("/wx/wxUser")
@RequestMapping("/wx/wxUser")
public class WxUserController {

    private WxUserService service;

    @ApiOperation("查询用户")
    @GetMapping("/{openId}")
    public WxUserDTO findOne(@PathVariable String openId) {
        WxUser wxUser = service.selectByIdOptional(openId).orElseThrow(WxUserInvalidException::new);
        return toDTO(wxUser);
    }

    @ApiOperation("根据openId列表查询用户列表")
    @PostMapping("/findMap")
    public Map<String, WxUserDTO> findMap(@RequestBody Collection<String> openIds) {
        if (openIds == null || openIds.isEmpty()) {
            return Collections.emptyMap();
        }

        WxUserSearchParams searchParams = new WxUserSearchParams();
        searchParams.setOpenIds(openIds);

        Collection<WxUser> wxUsers = service.selectAll(searchParams);

        return CollectionUtil.toMap(wxUsers, WxUser::getOpenId, this::toDTO);
    }

    @ApiOperation("查询用户数量")
    @GetMapping("/count")
    public int findCount(WxUserSearchParams searchParams) {
        return service.selectCount(searchParams);
    }

    private WxUserDTO toDTO(WxUser user) {
        WxUserDTO dto = new WxUserDTO();
        dto.setOpenId(user.getOpenId());
        dto.setNickName(user.getNickName());
        dto.setAvatarUrl(user.getAvatarUrl());

        return dto;
    }

    @Autowired
    public void setService(WxUserService service) {
        this.service = service;
    }
}
